package  com.hafu.dao;
import   com.hafu.model.RuKuMain;
import    com.hafu.util.DbUtil;
import    com.hafu.util.StringUtil;
import  java.sql.Connection;
import   java.sql.PreparedStatement;
import java.sql.ResultSet;
import  java.sql.SQLException;
import  java.util.ArrayList;
public class RuKuMainDao {
    public  int  addRuKuMain(RuKuMain ruku,Connection conn)throws  SQLException{
        String sql="insert into ruku_main(ruku_name,price,gys_name,rk_date)values(?,?,?,current_timestamp)";
        PreparedStatement    preparedStatement    =conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(1,ruku.getRukuName());
        preparedStatement.setBigDecimal(2,ruku.getPrice());
        preparedStatement.setString(3,ruku.getGysName());
        int i= preparedStatement.executeUpdate();
            if (i>0){
                ResultSet generatedKeys =preparedStatement.getGeneratedKeys();
                generatedKeys.next();
                return   generatedKeys. getInt(1);

            }else {
                return-1;
            }
        }

    public ArrayList<RuKuMain> getRuKuMainByName (RuKuMain ruku) {
        Connection conn=DbUtil.getConnection();
        String sql="select*from  ruku_main";
            if (!StringUtil.isEmpty(ruku.getRukuName())) {
                sql = sql + " where ruku_name like '%" + ruku.getRukuName() + "%'";
            }

            ArrayList<RuKuMain>list  =new  ArrayList<>();
        try  {
            PreparedStatement preparedStatement =conn.prepareStatement(sql);
            ResultSet resultSet =preparedStatement.executeQuery();
            while   (resultSet.next()){
                RuKuMain  rukuMain  =new   RuKuMain();
                rukuMain.setld(resultSet.getInt("id"));
                rukuMain.setRukuName(resultSet.getString("ruku_name"));
                rukuMain.setPrice(resultSet.getBigDecimal("price"));
                rukuMain.setGysName(resultSet.getString("gys_name"));
                rukuMain.setRkDate(resultSet.getString("rk_date"));
                list.add(rukuMain);
            }
        }catch   (SQLException  throwables){ throwables.printStackTrace();
        }
        return  list;
    }
    public  Boolean  updateRuKu(RuKuMain  ruKuMain){
        Connection  conn=DbUtil.getConnection();
        String  sql="update   ruku_main  set   ruku_name=?where  id=?";
        try{
            PreparedStatement    preparedStatement    =conn.prepareStatement(sql);
            preparedStatement.setString(1,ruKuMain.getRukuName());
            preparedStatement.setInt(2,ruKuMain.getld());
            int i=preparedStatement.executeUpdate();
            if (i>0){
                return true;
            }else return false;
        }catch  (SQLException  throwables){
            throwables.printStackTrace();
        }
        return false;
    }
}

